var data;
$(function(){
	//购物车按钮锁定
	$('.orderbox_btn_goIndent').bind('click',function(){
		if($(this).attr('readonly')==false){
			$(this).addClass('readonly').attr('readonly','readonly');
			$(this).unbind('click');
			makeOrder();
		}
	});
	
	//订单课程总价
	var orderPrice = $('#order_total_price').attr('price');
	//帐户余额
	var balance = $('#balance').text();
	if (Number(balance) < Number(orderPrice)){
		$('#balance_p').show();
		$('#balance_btn').hide();
		$('#payment_type').show();
		//金额不足50元付款方式处理
		changeTabShow();
	}else{
		$('#balance_p').hide();
		$('#balance_btn').show();
		$('#payment_type').hide();
	}
	
	//省市区联动
	renderAreaSelect();

	//邮编获取
	$("#add_province, #add_city, #add_country").click(function(){
		var country_id = $("#add_country").val();
		var _country_id = $("#country").val();
		if (country_id != _country_id) {
			zipSelect(country_id);
		}
	});
	
	//地址选择
	$('#address-list input:radio').live('click', function(){
		if(this.checked && this.value == '0'){
			$('#add_id').attr('value', 0);
			$('#realname').attr('value', '');
			$('#province').attr('value', 0);
			$('#city').attr('value', 0);
			$('#country').attr('value', 0);
			$('#address').attr('value', '请填写详细路名及门牌号');
			$('#zipcode').attr('value', '');
			$('#phone').attr('value', '');
			checkSelect('add_province', '');
			$('#details-form').show();
			$('#next_step').hide();
		}else{
			$('#details-form').hide();
			$('#next_step').show();
		}
	});
	
	//促销订单信息
	salesList();
        //金额不足50元付款方式处理
        changeTabShow();
  	
});

//促销订单信息
var salesList = function(){
	if($('#sales_json').html()){
		data = $('#sales_json').html();
		data = eval('(' + data + ')');
		var length = data.sales.length;
		var html = '';
		var total_price = parseInt($('#order_total_price').text());
		for(var i = 0;i<length;i++){
			var price = parseInt(data.sales[i].price);
			var rule_id = data.sales[i].rule_id;
			if(price<total_price || price==total_price){
				var content = data.sales[i].content;
				html = html+'<input class="sales_radio" type="radio" value="'+rule_id+'" name="data[promotionOrder]"><span>'+content+'</span>';
			}
		}
		$('#sales_list').empty();
		$('#sales_list').html(html);
		$($('.sales_radio')[0]).attr('checked',true);
	}
}

/*
 * 加入收藏
 *
 * maxiaoyu
 */
var addToCustWish = function(course_id, url){	
	$.ajax({
		url		: '/course/addFavorite/' + course_id,
		type 	: 'post',
		dataType: 'html',
		success : function (msg){
			if (msg == 0){
				window.location.href = '/users/logReg/' + url;
			}else{
				$('#js_roundWinDiv').hide();
				var html = '<div style="padding-top: 0px;" class="win_title" >'+msg+'<br></div>'+
			               '<button type="submit" class="submit_btn" style="margin-left: 0px; margin-right: 0px;">确定</button>';
				$('#js_winhtml').html(html);
				var left = $('#add'+course_id).offset().left-$('#js_roundWinDiv').width();
				var top = $('#add'+course_id).offset().top-$('#js_roundWinDiv').height();
				$('#js_roundWinDiv').css('top',top+'px');
				$('#js_roundWinDiv').css('left',left+'px');
				$('#js_roundWinDiv').show();
				
				$('.submit_btn').click(function(){
					$('#js_roundWinDiv').hide();
				});
				$('.closeBtn').click(function(){
				   $('#js_roundWinDiv').hide();
				});
			}
		}	
	});
}	

/*
 *  删除购物车中的课程
 *
 *  maxiaoyu
 */
var deltToCustWish = function(id){
	$('#js_roundWinDiv').hide();
    var html = '<div style="padding-top: 0px;" class="win_title" >您确定删除该课程吗？<br></div>'+
               '<button type="submit" class="submit_btn" style="margin-left: 0px; margin-right: 0px;">确定</button>'+
			   '<button class="cancel_btn" type="submit" style="margin-right:0;">取消</button>';
	$('#js_winhtml').html(html);
	var left = $('#delt'+id).offset().left-$('#js_roundWinDiv').width();
	var top = $('#delt'+id).offset().top-$('#js_roundWinDiv').height()-35;
	$('#js_roundWinDiv').css('top',top+'px');
	$('#js_roundWinDiv').css('left',left+'px');
	$('#js_roundWinDiv').show();
	
	//确定按钮方法
	$('.submit_btn').click(function(){
		$('#js_roundWinDiv').hide();
		//用户第一次点击删除按钮时调用
		$.ajax({
			url 	: '/shoppingcart/delJudge/',
			dataType: 'json',
			type 	: 'post',
			success : function (msg){
				if (msg == 1){
					var html = '<div style="padding-top: 0px;padding-bottom:20px;" class="win_title" >您删除的课程将会出现在页<br/>面底部最近浏览过的课程中</div>';
					$('#js_winhtml').html(html);
					var left = ($(document).width()-$('#js_roundWinDiv').width())/2;
					var top = 200;
					$('#js_roundWinDiv').css('top',top+'px');
					$('#js_roundWinDiv').css('left',left+'px');
					$('#js_roundWinDiv').show();
					$('.winHtml').attr('id','show_winhtml');
					setInterval(function(){
						 $('#show_winhtml').hide();
						 $('.winHtml').attr('id','js_roundWinDiv');
					},3000);
					setInterval(function(){
			 			window.location.href='/shoppingcart/delcart/'+id;
					},3000);
				}else{
					setInterval(function(){
						 window.location.href='/shoppingcart/delcart/'+id;
					},1500);
				}
			},
			error : function (){
				alert('数据读取错误...');
			}
		});
	});
	//取消按钮方法
	$('.cancel_btn,.closeBtn').click(function(){
	   $('#js_roundWinDiv').hide();
	});
}

/*
 * 清空购物车
 * 
 * maxiaoyu
 */
var emptycart = function(){
	$('#js_roundWinDiv').hide();
	var html = '<div style="padding-top: 0px;" class="win_title" >您确定清空购物车吗？<br></div>'+
               '<button type="submit" class="submit_btn" id="submit_btn" style="margin-left: 0px; margin-right: 0px;">确定</button>'+
			   '<button class="cancel_btn" type="submit" style="margin-right:0;">取消</button>';
	$('#js_winhtml').html(html);
	var left = ($(document).width()-$('#js_roundWinDiv').width())/2;
	var top = 220;
	$('#js_roundWinDiv').css('top',top+'px');
	$('#js_roundWinDiv').css('left',left+'px');
	$('#js_roundWinDiv').show();
	$('#submit_btn').click(function(){
		$.ajax({
			url : '/shoppingcart/emptycart/',
			type : 'json',
			dataType : 'post',
			success : function (msg){
				if (msg == true){
					var html = '<div style="padding-top: 0px;" class="win_title">您的购物车中已没有课程了！</div>'+
                   			   '<a href="/search/"><button type="submit" id="submit_btn_2" class="submit_btn" style="margin-left: 0px; margin-right: 0px;">继续购物</button></a>';
				   	$('#js_winhtml').html(html);
				   	$('.closeBtn').click(function(){
						$('#js_roundWinDiv').hide();
						window.location.reload(); 
				   	});
				}
			},
			error : function (){
				alert('读取数据错误..');
			}
		});
	});
	$('.closeBtn,.cancel_btn').click(function(){
  		$('#js_roundWinDiv').hide();
	});
}

/*
 * 浏览过的课程加入购物车时
 *  判断是否加入过购物车
 *  
 *  maxiaoyu
 */
function addcart(id){
	$.ajax({
		url : '/shoppingcart/addcartJudge/'+id,
		type : 'post',
		dataType : 'json',
		success : function (msg){
			if (msg == 1){
				alert('您已添加到了购物车！');
			}else{
				window.location.href='/shoppingcart/addcart/'+id;
			}
		},
		error : function (){
			alert('读取数据错误..');
		}
	});
}

/*
 * 购物车验证
 */
function makeOrder () {
    $.ajax({
        url :'/shoppingcart/makecart/',
        type:'post',
        dataType:'json',
        success: function (msg) {
        	if (msg.sign == 1 || msg.sign == 2) {
        		window.location.href = msg.url;
        	}
        	if (msg.sign == 5) {
        		for(var i=0; i<msg.errorCids.length; i++){
					$("#cart" + msg.errorCids[i]).css('backgroundColor', '#F5D3D3');
				}
				   	
				var html = '<div style="padding-top: 0px;" class="win_title" >' + msg.errorMsg + '</div>' +
			   '<button class="cancel_btn" type="submit" style="margin-right:0;">取消</button>' +
               '<a class ="submit_btn" href="' + msg.url + '">继续结算</a>';
				$('#js_winhtml').html(html);
				$('#js_winhtml').css('width','500px');
				var left = ($(document).width()-$('#js_roundWinDiv').width())/2;
				var top = 220;
				$('#js_roundWinDiv').css('top',top+'px');
				$('#js_roundWinDiv').css('left',left+'px');
				$('#js_roundWinDiv').show();
				//取消按钮方法
				$('.cancel_btn,.closeBtn').click(function(){
	   				$('#js_roundWinDiv').hide();
	   				$('#js_winhtml').css('width','270px');
				});
        	}
        	if (msg.sign == 3 || msg.sign == 4) {
        		for(var i=0; i<msg.errorCids.length; i++){
					$("#cart" + msg.errorCids[i]).css('backgroundColor', '#F5D3D3');
				}
				
				var html = '<div style="padding-top: 0px;" class="win_title" >' + msg.errorMsg + '</div>' +
			   '<button class="cancel_btn" type="submit" style="margin-right:0;">确定</button>';
				$('#js_winhtml').html(html);
				$('#js_winhtml').css('width','500px');
				var left = ($(document).width()-$('#js_roundWinDiv').width())/2;
				var top = 220;
				$('#js_roundWinDiv').css('top',top+'px');
				$('#js_roundWinDiv').css('left',left+'px');
				$('#js_roundWinDiv').show();
				//取消按钮方法
				$('.cancel_btn,.closeBtn').click(function(){
	   				$('#js_roundWinDiv').hide();
	   				$('#js_winhtml').css('width','270px');
				});
        	}
        }
    });
};

/*
 * 学习卡充值展开
 */
function cardShow() {
	$('#rechargeCard').toggle();
}

/*
 * 学习卡充值
 */
$(function () {
	$("#stuCardBtn").click(function(){
		var cardPwd = $("#stuCardPrice").val();
        if(cardPwd == '' || cardPwd == 0 || cardPwd.match("^[0-9]{12,20}$") == null ){
            alert('充值卡填写错误');
            return;
        }

		$.ajax({
		   type: 'POST',
		   url:  '/Orders/aStudyCardRechare/' + cardPwd + '/',
		   success: function(msg){
                if(msg == '0'){
                    alert('充值失败,请重试！！！');
                }else if(msg == '3'){
					alert('卡已使用');
                }else if(msg > 0 && msg != 4){
					alert('充值成功，充值金额为:' + msg);
                    _price = parseInt(msg); 
                    var balance = parseInt($('#balance').text()) + _price;
					$('#balance').text(balance+'.00');
					if(parseInt($('#balance').text()) > parseInt($('#order_total_price').text()) || parseInt($('#balance').text()) == parseInt($('#order_total_price').text())){
						$('#payment_type').hide();
						$('#balance_btn').show();
						$('#pay_type').attr('value','3');
					}else{
						$('#payment_type').show();
						$('#balance_btn').hide();
						$('#pay_type').attr('value',$('#pay_type').attr('befor'));
						var balance_payment = parseInt($('#order_total_price').text())-parseInt(balance);
						$('#balance_payment').text(balance_payment+'.00');
						$('#balance_bank').text(balance+'.00');
					}
				}
		   }
		});
	});
});

/*
 * 省市区联动
 */
function renderAreaSelect () {
    var defaults = {
        s1:'add_province',
        s2:'add_city',
        s3:'add_country',
        v1:$("#province").val(),
        v2:$("#city").val(),
        v3:$("#country").val()
    };
 	$('#add_province').empty('');
    threeSelect(defaults);
};

/*
 * 邮编选择
 */
function zipSelect(id){
	$.ajax({
		type: "GET",
		url: '/json/wss_zipcode.json?' + generateMixed(12),
		dataType: "json",
		timeout: 7000,
		success: function(result) {
			if (result != '') {
				$.each(result, function(i, j) {
					if (i == id) {
						var zipcode = j['zipcode'];
						$('#zipcode').attr('value',zipcode);
					}
				});
			}
		},
		error: function() {
			alert('数据读取错误..');
		}
	});
};

/*
 * 地址修改
 */
function updateAddress (id) {
	var realname = $('#recipient_'+id).text();
	var province = $('#province_id_'+id).val();
	var city = $('#city_id_'+id).val();
	var country = $('#county_id_'+id).val();
	var address = $('#recipient_adds_'+id).text();
	var zipcode = $('#recipient_zipcode_'+id).text();
	var phone = $('#recipient_phone_'+id).text();
	
	$('#add_id').attr('value', id);
	$('#realname').attr('value', realname);
	$('#province').attr('value', province);
	$('#city').attr('value', city);
	$('#country').attr('value', country);
	$('#address').attr('value', address);
	$('#zipcode').attr('value', zipcode);
	$('#phone').attr('value', phone);
	checkRadio('addid[]', id);
	renderAreaSelect();
	$('#details-form').show();
	$('#next_step').hide();
}
var changeDisabled;
$(function(){
	$('#realname,#add_province,#address,#zipcode,#phone').bind({
		blur:function(){
			FormValidation(this);
		},
		focus:function(){
			var _tipsbox=$(this).nextAll('label.tips');
			_tipsbox.removeClass('moren');
			if(_tipsbox.hasClass('eer')){
				
			}else{
				_tipsbox.addClass('default');
			}
		}
	});
	
	
	$('#address_submit_btn').bind('click',function() {
		FormValidation($('#realname')[0]);
		FormValidation($('#add_province')[0]);
		FormValidation($('#address')[0]);
		FormValidation($('#zipcode')[0]);
		FormValidation($('#phone')[0]);
		var _err=$('.add-con .err_info');
		if(_err.length != 0){
			return false;
		}else{
			var realname = $.trim($("#realname").val());
			var province_id = $("#add_province").val();
			var city_id = $("#add_city").val();
			var country_id = $("#add_country").val();
			var address = $.trim($("#address").val());
			var zipcode = $("#zipcode").val();
			var phone = $("#phone").val();
			var id = $("#add_id").val();
			var params = "id="+id+"&realname="+realname+"&province_id="+province_id+"&city_id="+city_id+"&country_id="+country_id+"&address="+address+"&zipcode="+zipcode+"&phone="+phone;

			$.ajax({
				type	:'POST',
			   	url		:'/shoppingcart/saveStuAdds/',
			   	dataType:'json',
        		timeout	:7000,
        		data	:params,
        		success	:function(msg){
        			if (msg.sign == true) {
        				if (msg.type == 1) {
        					var addList = $("#address-list").html();
        					var	addMsg = 	'<div class="address_list">'; 
        					 	addMsg +=	'<input type="radio" id="addid[]" name="data[addid]" value="' +msg.addId+ '" /> ';
	        					addMsg +=	'<span id="recipient_' +msg.addId+ '">' +realname+ '</span>，';
	        					addMsg +=	'<input type="hidden" id="province_id_' +msg.addId+ '" value="' +province_id+ '" />';
	        					addMsg +=	'<input type="hidden" id="city_id_' +msg.addId+ '" value="' +city_id+ '" />';
	        					addMsg +=	'<input type="hidden" id="county_id_' +msg.addId+ '" value="' +country_id+ '" />';
	        					addMsg +=	'<span id="recipient_area_' +msg.addId+ '">' + msg.province + msg.city + msg.country + '</span> ';
	        					addMsg +=	'<span id="recipient_adds_' +msg.addId+ '">' +address+ '</span>，';
	        					addMsg +=	'<span id="recipient_zipcode_' +msg.addId+ '">' +zipcode+ '</span>，';
	        					addMsg +=	'<span id="recipient_phone_' +msg.addId+ '">' +phone+ '</span> ';
	        					addMsg +=	'【<a href="javascript:updateAddress(' +msg.addId+ ');">修改</a>】';
	        					addMsg +=	'</div>';
	        				$("#address-list").html(addMsg + addList);			
        				}
        				if (msg.type == 2) {
        					$('#recipient_' + msg.addId).html(realname);
        					$('#province_id_' +msg.addId).attr('value', province_id);
        					$('#city_id_' +msg.addId).attr('value', city_id);
        					$('#county_id_' +msg.addId).attr('value', country_id);
        					$('#recipient_area_' + msg.addId).html(msg.province + msg.city + msg.country);
        					$('#recipient_adds_' + msg.addId).html(address);
        					$('#recipient_zipcode_' + msg.addId).html(zipcode);
        					$('#recipient_phone_' + msg.addId).html(phone);
        				}
        				$('#details-form').hide();
        				$('#next_step').show();
        				checkRadio('addid[]', msg.addId);
        			}else{
        				alert('信息保存失败..');
        			}
        		},
        		error	:function() {
					alert('数据读取错误..');
				}
       		});
		}
	});
	
	/**支付方式tab切换*/
	var tabLi = $('.rank-menu > li');
	var tabLiA = $('.rank-menu > li a');
	var tabContent = $('#payment_type .tab-list');
	tabLi.live('click', function(){
		var addId = $("input[name='data[addid]']:checked").val();
		if ($(this).index() == 0 && addId == 0) {
			$('#next_step').hide();
		}else{
			$('#next_step').show();
		}
		for(var i=0;i<tabLi.length;i++){
			if(i==$(this).index()){
				$(tabLiA).eq(i).addClass('current'); 
				$(tabContent).eq(i).removeClass('hover-content');
				$('#pay_type').attr('value',i);
				$('#pay_type').attr('befor',i);
			}else{
				if($(tabLiA).eq(i).hasClass('current')){
				   $(tabLiA).eq(i).removeClass('current');
				   $(tabContent).eq(i).addClass('hover-content');
				}
			}
		}
	});
	
	/**支付方式tab切换*/
	var select_obj = $("select[name='data[coupon][]']");
	for(var i=0;i<select_obj.length;i++){
		$(select_obj[i]).change(function(){
			var option_list = $(this)[0].children;
			for(var j=0;j<option_list.length;j++){
				if($(option_list[j]).attr('selected')&&$(this).attr('value')==$(option_list[j]).attr('value')){
					$(this).attr('value',$(option_list[j]).attr('value'));
					var option_value = $(option_list[j]).attr('price');
					var select_id = $(option_list[j]).attr('name');
					if($('#'+select_id)[0].children[j].style.color=='rgb(204, 204, 204)' || $('#'+select_id)[0].children[j].style.color=='#ccc'){
						 var value = $('#'+select_id+'_hidden').attr('value');
						 $($('#'+select_id)[0].children[value]).attr('selected','true');
					}else{
						 changeDisabled(select_id,j,option_value);
					}
				}
			}
		});
	}
	
	changeDisabled = function(select_id,option_id,price){
		var price = parseInt(price);//选中当前下拉框的值
		var select_hidden = parseInt($('#'+select_id+'_hidden').attr('value'));//选中当前下拉框的隐藏框的值
		var sel1_price = parseInt($('#'+select_id+'_price').text());//选中当前下拉框的小计值
		var total_price = parseInt($('#order_total_price').text());//需为此订单支付的值
		var coupon_total_price = parseInt($('#coupon_total_price').text());//节省的值
		var balance = Number($('#balance').text());//帐户余额
		var price_hidden = $($(select_obj[0])[0].children[select_hidden]).attr('price');//操作前的代金券值
		var total_price_1 = parseInt($('#total_price').text());//课程价格总计
		var rebate_price = parseInt($('#'+select_id+'_hidden').attr('price'));//优惠价
		var price_hidden = parseInt($('#'+select_id+'_price_hidden').val());
		
		if(price_hidden == ''){
			price_hidden = 0;
		}else{
			price_hidden = parseInt(price_hidden);
		}
		if(option_id == 0){//选择奖学金
			for(var i=0;i<select_obj.length;i++){
				$($(select_obj[i])[0].children[option_id]).css('color','#000');
			  	$($(select_obj[i])[0].children[select_hidden]).css('color','#000');
		   	}
			var price_hidden = $('#'+select_id+'_price_hidden').val();//计算小计值
			$('#'+select_id+'_price').text(price_hidden);
			var length = $('.min_price').size();
			var min_price = 0;
			for(var i =0;i<length;i++){
				min_price = parseInt($($('.min_price')[i]).text())+min_price;
			}
			$('#order_total_price').text(min_price);
			var sum_price = total_price_1 - min_price;//计算需支付的值
			$('#coupon_total_price').text(sum_price);//计算节省的值
		}else{//选择奖学金
		   	for(var i=0;i<select_obj.length;i++){
			  	$($(select_obj[i])[0].children[option_id]).css('color','#ccc');
			  	$($(select_obj[i])[0].children[select_hidden]).css('color','#000');
		   	}
			if(price_hidden<price){
				var min_price= 0;
			}else{
				var min_price= price_hidden - price;
			}
			$('#'+select_id+'_price').text(min_price);//计算小计值
			var length = $('.min_price').size();
			var min_price = 0;
			for(var i =0;i<length;i++){
				min_price = parseInt($($('.min_price')[i]).text())+min_price;
			}
			$('#order_total_price').text(min_price);
			var sum_price = total_price_1 - min_price;//计算需支付的值
			$('#coupon_total_price').text(sum_price);//计算节省的值
		}
		if(balance > parseInt($('#order_total_price').text()) || balance == parseInt($('#order_total_price').text())){
			$('#payment_type').hide();
			$('#balance_btn').show();
			$('#pay_type').attr('value','3');
		}else{
		   	$('#payment_type').show();
			$('#balance_btn').hide();
			$('#pay_type').attr('value',$('#pay_type').attr('befor'));
			var balance_payment = parseInt($('#order_total_price').text())-parseInt(balance);
			$('#balance_payment').text(balance_payment+'.00');
		}
	  	$('#'+select_id+'_hidden').attr('value',option_id);
		salesList();
     	changeTabShow();
	}
	/**用余额付款复选框*/
	$(':checkbox[name="is_balance"]').click(function(){
	   $('#balance_title').toggle();
	});
	
});	

function setState (obj,cls,text){
	var _tips=$(obj);
	var _defalut_text=_tips.text();
	_tips.find('p').remove();
	if(cls=='eer'){
		_tips.append('<p class="err_info">'+text+'</p>');
	}
};

function checkForm(obj,func){
	var rules={
		mobile		: "^1[3|5|8][0-9][0-9]{8}$",
		isCN		: '^[chr(0xa1)-chr(0xff)]+$',
		numeric		: "^[0-9]+$",
		loginname	: "^[a-z][a-z0-9-_.]+$",
		phone		: "^([0-9]{0}|[0-9]{3,4})[-]{0,1}[0-9]{7,8}$",
		idcard		: "^([0-9]{15}|[0-9]{18})$",
		zipcode		: "^[0-9]{6}$"
	};
	var arg=arguments;
	if(arg.length>0){
		var reg	= new RegExp(rules[obj.type] , "gi");
		var result	= reg.test(obj.value)?true:false;
		if(arg.length>1&&typeof(arg[1])=='function'){ 
			return func(result);
		}else{
			return result;
		}
	}else{
		alert('请设置您要检查的内容');
	}
};

function FormValidation(n){
	var rules={
		realname:function(){
		    var _name_err = $('#name_err')[0];
			if(n.value.length>1){ 
				checkForm({'value':n.value,'type':'isCN'},function(t){
					if(t){
						setState(_name_err,'eer','请输入真实姓名');
					}else{
						setState(_name_err,'suc','');
					};
				});
			}else{
				setState(_name_err,'eer','请输入真实姓名');
			}
		},
		add_province:function(){
			var _province_err = $('#province_err')[0];
			var _province = $('#add_province').val();
			if(_province!=''){ 
				setState(_province_err,'suc','');
			}else{
				setState(_province_err,'eer','请选择省市');
			}
		},
		invoice:function(){
			var _invoice_err = $('#invoice_err')[0];
			var _invoice = $('#invoice').val();
			if(_invoice!=''){ 
				setState(_invoice_err,'suc','');
			}else{
				setState(_invoice_err,'eer','请输入发票类型');
			}
		},
		zipcode:function(){
			var _zipcode_err = $('#zipcode_err')[0];
			checkForm({'value':n.value,'type':'zipcode'},function(t){
			var _box=$('#zipcode')[0];
				if(t){
					setState(_zipcode_err,'suc','');
				}else{
					setState(_zipcode_err,'eer','请输入邮政编码');
				}
			});
		},
		phone:function(){
			var _phone_err = $('#phone_err')[0];
			checkForm({'value':n.value,'type':'mobile'},function(t){
			var _box=$('#phone')[0];
				if(t){
					setState(_phone_err,'suc','');
				}else{
					setState(_phone_err,'eer','填写的手机号码错误');
				}
			});
		},
	   address:function(){
		    var _address_err = $('#address_err')[0];
			var _address = $('#address').val();
			if(_address!=''){ 
				setState(_address_err,'suc','');
			}else{
				setState(_address_err,'eer','请输入详细地址');
			}
	   }
	};
	rules[n.id]();
};

$(function(){
	var isCheckBox = true;
	var isNameTitle = false;
	/**索取赠品**/
  	$(":checkbox").click(function(){
		if(!$(this).attr('checked')){
	    	var checkbox = $(":checkbox");
		  	for(var i = 0; i<checkbox.length;i++){
				if($(checkbox[i]).attr('checked')){
					isCheckBox = true;
				   	return true;
			   	}else{
			       	isCheckBox = false;
			   	}
		  	}
	  	}else{
	      	isCheckBox = true;
	  	}
	  	if(isCheckBox || isNameTitle){
		  	$('.add_user_con').removeClass('hover-content');
	  	}else{
	     	$('.add_user_con').addClass('hover-content');
	  	}
  	});	
	
	/**索取发票**/
	$("#invoice_head").blur(function(){
		if($(this).val()!=0){
			isNameTitle = true;
		}
		if(isCheckBox || isNameTitle){
			$('.add_user_con').removeClass('hover-content');
		}else{
			$('.add_user_con').addClass('hover-content');
		}
	});
	
});

/*
 * 附属品展现
 */
var changeShow = function(id){
	$('#'+id).toggle();
	if($('#'+id+'-tip').hasClass('title_border')){
		$('#'+id+'-tip').removeClass('title_border');
	}else{
   		$('#'+id+'-tip').addClass('title_border');
	}
}

/*
 * 赠品提交
 */
function giveawaySub () {
	var orderNum = $("#order_num").text();
	var giveaways = getCheckedValue("giveaway[]");
	var invoiceHead = $.trim($("#invoice_head").val());
	var invoiceType = $("#invoice_type").val();
	var addId = $("input[name='data[addid]']:checked").val();
	var sendTime = $("input[name='data[sendTime]']:checked").val();
	var note = $.trim($("#note").val());
	var params = 'orderNum='+orderNum+'&giveaways='+giveaways+'&invoiceHead='+invoiceHead+'&invoiceType='+invoiceType+'&addId='+addId+'&sendTime='+sendTime+'&note='+note;
	
	$.ajax({
		type	:'POST',
	   	url		:'/shoppingcart/saveSendGiveway/',
	   	dataType:'json',
		timeout	:7000,
		data	:params,
		success	:function(msg){
			if (msg.sign == false){
				if (msg.type == 1) {
					window.location.href = "/users/logReg/";
				}
				if (msg.type == 2) {
					window.location.reload(); 
				}
				if (msg.type == 3) {
					var html = '<div style="padding-top: 0px;" class="win_title" >'+msg.msg+'<br></div>'+
			              	   '<button type="submit" class="submit_btn"  id="submit_btn" style="margin-left: 0px; margin-right: 0px;">确定</button>';
					$('#js_winhtml').html(html);
					var left = ($(document).width()-290)/2;
					$('#js_roundWinDiv').css('left',left+'px');
					$('#js_roundWinDiv').css('top','550px');
					$('#js_roundWinDiv').show();
	
					$('.submit_btn,.closeBtn').click(function(){
						$('#js_roundWinDiv').hide();
					});
				}
			}else{
				$('#is_send').hide();
				var html = '<div style="padding-top: 0px;" class="win_title">提交成功<br></div><div>&nbsp;</div>';
		        setInterval(function(){
					$('#js_roundWinDiv').hide();
					$('.winHtml').attr('id','js_roundWinDiv');
		        },3000);

				$('#js_winhtml').html(html);
				var left = ($(document).width()-290)/2;
				$('#js_roundWinDiv').css('left',left+'px');
				$('#js_roundWinDiv').css('top','550px');
				$('#js_roundWinDiv').show();
			}
		},
		error	:function() {
			alert('数据读取错误..');
		}
	});
}

/*
 * 使用教师认证优惠
 */
function useTeacherIdent (courseId, id) {
	//处理选中当前下拉框
	radioChange();
	
	if ($('#sel'+id).val()){
		if($('#sel'+id).attr('value')!=0){
			$($('#sel'+id)[0].children[0]).attr('selected','true');
			changeDisabled('sel'+id, 0, 0);
		}
	}
	if ($('#sel'+id).length>0){
		$('#sel'+id).attr("disabled","disabled");
	}
	var sel_price = parseInt($('#sel' +id+ '_price').text());//选中当前下拉框的小计值
	var total_price = parseInt($('#order_total_price').text());//订单支付总额
	var balance = parseInt($('#balance').text());//帐户余额
	$('#sel' +id+ '_price').text('0');
	if(sel_price != 0){
		if(total_price > sel_price){
			$('#order_total_price').text(total_price-sel_price);
		}else{
			$('#order_total_price').text('0');
		}
		if(balance>parseInt($('#order_total_price').text()) || balance==parseInt($('#order_total_price').text())){
			$('#balance_btn').show();
			$('#payment_type').hide();
			$('#pay_type').attr('befor',$('#pay_type').val());
			$('#pay_type').attr('value','3');
		}
		salesList();
      	changeTabShow();
	}
};

/*
 * 不使用教师认证优惠
 */
function unTeacherIdent (courseId, id){
	//处理选中当前下拉框
	radioChange();
	
	if($('#sel'+id).length>0){
		$('#sel'+id).removeAttr("disabled");
	}
	var sel_price = parseInt($('#sel' +id+ '_price_hidden').val());//选中当前下拉框的小计值
	var total_price = parseInt($('#order_total_price').text());//订单支付总额
	var balance = parseInt($('#balance').text());//帐户余额
	$('#sel' +id+ '_price').text(sel_price);
	if(sel_price != 0){
		$('#order_total_price').text(total_price+sel_price);
		if(balance>parseInt($('#order_total_price').text()) || balance==parseInt($('#order_total_price').text())){
			$('#balance_btn').show();
			$('#payment_type').hide();
		}else{
			$('#balance_btn').hide();
			$('#payment_type').show();
			$('#pay_type').attr('befor','3');
			$('#pay_type').attr('value',$('#pay_type').val());
		}
		salesList();
     	changeTabShow();
	}
}

//处理选中当前下拉框
function radioChange(){
	var length = $(":radio").length;
	var count = 0;
	var radio_count = $('#t_ident_count').val();

	for(var i=0;i<length;i++){
		if($($(":radio")[i]).attr('checked') && $($(":radio")[i]).attr('tident')){
			var name = $($(":radio")[i]).attr('tident');
			name = name.split('_');
			if(name[1] == 'check'){
				if($($(":radio")[i]).attr('value')!=0){
					count = count + 1;					
				}
			}
		}
	}

	if(count == radio_count){
		for(var i=0;i<length;i++){
			if($($(":radio")[i]).attr('tident')){
				var name = $($(":radio")[i]).attr('tident');
				name = name.split('_');
				if(name[1] == 'check'){
					$($(":radio")[i]).attr("disabled","disabled");
					if($($(":radio")[i]).attr('checked')){
						if($($(":radio")[i]).attr('value')!=0){
							$($(":radio")[i]).removeAttr("disabled");
							$($(":radio")[i-1]).removeAttr("disabled");
						}
					}
				}
			}
		}
	}

	if(count<radio_count){
		for(var i = 0;i<length;i++){
			if($($(":radio")[i]).attr('tident')){
				var name = $($(":radio")[i]).attr('tident');
				name = name.split('_');
				if(name[1] == 'check'){
					$($(":radio")[i]).removeAttr("disabled");
				}
			}
		}
	}
}

//金额不足50元处理货到付款
function changeTabShow(){
	var total_price = parseInt($('#order_total_price').text());
	var tabLi = $('.rank-menu > li');
	var tabLiA = $('.rank-menu > li a');
	var tabContent = $('#payment_type .tab-list');
	//订单课程总价
	var orderPrice = Number($('#order_total_price').text());
	//帐户余额
	var balance = Number($('#balance').text());
	
	if(total_price<50){
		$(tabLi).eq(0).hide();
		for(var i=0;i<tabLi.length;i++){
			if(i==1){
				$(tabLiA).eq(i).addClass('current'); 
				$(tabContent).eq(i).removeClass('hover-content');
				$('#pay_type').attr('value',i);
				$('#pay_type').attr('befor',i);
			}else{
				if($(tabLiA).eq(i).hasClass('current')){
				   $(tabLiA).eq(i).removeClass('current');
				   $(tabContent).eq(i).addClass('hover-content');
				}
			}
		}
	}else{
		$(tabLi).eq(0).show();
		for(var i=0;i<tabLi.length;i++){
			if(i==0){
				$(tabLiA).eq(i).addClass('current'); 
				$(tabContent).eq(i).removeClass('hover-content');
				$('#pay_type').attr('value',i);
				$('#pay_type').attr('befor',i);
			}else{
				if($(tabLiA).eq(i).hasClass('current')){
				   $(tabLiA).eq(i).removeClass('current');
				   $(tabContent).eq(i).addClass('hover-content');
				}
			}
		}
	}
	
	if ((balance > orderPrice) || (balance == orderPrice)){
		$('#pay_type').attr('value',3);
		$('#pay_type').attr('befor',3);
	}
}